package com.longcai.cm.moudules.system.controller;

import com.longcai.cm.base.aop.Log;
import com.longcai.cm.bean.R;
import com.longcai.cm.common.utils.StringUtils;
import com.longcai.cm.moudules.system.domain.SysMenus;
import com.longcai.cm.moudules.system.service.SysMenusService;
import com.longcai.cm.moudules.system.utils.CmTreeUtils;
import com.longcai.cm.moudules.system.utils.UUID;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 【系统管理模块】----------菜单模块
 *
 * @author chenyue1993
 */
@RestController
@RequestMapping("/sysMenus")
@Api(value = "系统管理-菜单", tags = "系统管理-菜单")
@ApiSort(1)
public class SysMenusController {


    @Resource
    private SysMenusService sysMenusService;

    /**
     * 【API】----  获取整个资源菜单树 （树形结构---树形格式 (children为子级数据 )
     *
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return R
     */

    @Log(value = "获取菜单资源", type = "1")
    @PostMapping("/getMenuTree")
    @RequiresPermissions("menuList:list")
    public R getMenuTree(HttpServletRequest request, HttpServletResponse response) {

        List<SysMenus> allMenu = sysMenusService.getAllOrderedMenuList();
        //获取树形结构的所有菜单信息
        List<Map<String, Object>> menuTreeList = CmTreeUtils.getTreeList(allMenu);
        return R.success(menuTreeList);
    }


    /**
     * 保存菜单信息
     *
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return R
     */
    @Log(value = "保存菜单资源", type = "1")
    @PostMapping("/save")
    public R save(SysMenus vo, HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            sysMenusService.updateById(vo);
        } else {
            vo.setId(UUID.get());
            sysMenusService.save(vo);
        }
        return R.success();
    }


    /**
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return R
     */
    @Log(value = "删除菜单资源", type = "1")
    @PostMapping("/delete")
    public R delete(HttpServletRequest request, HttpServletResponse response) {
        String ids = request.getParameter("ids");
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            sysMenusService.removeById(idString);
        }
        return R.success();
    }

}
